package cn.chencq.demo.thrift.test.client;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import cn.chencq.demo.thrift.service.IHelloWorldService;

/**
 * 客户端
 * 
 * @author chencq
 *
 */
public class HelloWorldSimpleClient {

	public static final String SERVER_IP = "localhost";
	public static final int SERVER_PORT = 8090;// Thrift server listening port
	public static final int TIMEOUT = 30000;

	public void startClient(String userName) {
		// 传输层
		TTransport transport = null;
		try {
			transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);

			// 协议层和服务端一致
			TProtocol protocol = new TBinaryProtocol(transport);
			transport.open();

			// 创建RPC客户端
			IHelloWorldService.Client client = new IHelloWorldService.Client(protocol);
			// 调用服务
			String result = client.sayHello(userName);
			System.out.println("Thrift client result =: " + result);
		} catch (TTransportException e) {
			e.printStackTrace();
		} catch (TException e) {
			e.printStackTrace();
		} finally {
			if (null != transport) {
				// 关闭句柄
				transport.close();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		HelloWorldSimpleClient client = new HelloWorldSimpleClient();
		client.startClient("Tom");
	}
}